package com.iot.lemon.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;

import com.alibaba.dubbo.config.annotation.Service;
import com.iot.lemon.mapper.SysOrganizationMapper;
import com.iot.lemon.mapper.SysUserRoleMapper;
import com.iot.lemon.model.SysOrganization;
import com.iot.lemon.model.SysUser;
import com.iot.lemon.model.SysUserRole;
import com.iot.lemon.model.TVillage;
import com.iot.lemon.service.SysOrganizationService;
import com.iot.lemon.service.SysUserService;
import com.iot.lemon.service.TVillageService;

import top.ibase4j.core.base.BaseServiceImpl;
import top.ibase4j.core.util.DataUtil;
import top.ibase4j.core.util.InstanceUtil;

/**
 * <p>
 * 组织 服务实现类
 * </p>
 *
 * @author ShenHuaJie
 * @since 2018-08-04
 */
@Service(interfaceClass = SysOrganizationService.class)
@CacheConfig(cacheNames = "SysOrganization")
public class SysOrganizationServiceImpl extends BaseServiceImpl<SysOrganization, SysOrganizationMapper>
implements SysOrganizationService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private TVillageService villageService;

    @Override
    public SysOrganization update(SysOrganization record) {
        boolean add = record.getId() == null;
        SysOrganization result = super.update(record);
        if (add) {
            SysUser sysUser = null;
            if (DataUtil.isNotEmpty(record.getManagerAccount()) || DataUtil.isNotEmpty(record.getManagerPhone())
                || DataUtil.isNotEmpty(record.getManagerName())) {
                sysUser = new SysUser().setAccount(record.getManagerAccount()).setPhone(record.getManagerPhone());
                sysUser.setUserName(record.getManagerName());
                sysUser.setPassword(record.getManagerPassword());
                sysUser.setOrgaId(result.getId());
                sysUser.setCreateBy(result.getUpdateBy());
                sysUser.setUpdateBy(result.getUpdateBy());
                if ("1".equals(record.getOrgaType())) {
                    sysUser.setPosition("公司管理员");
                    sysUser = sysUserService.update(sysUser);
                    addSysUserRole(result, sysUser.getId(), 2L);
                } else if ("2".equals(record.getOrgaType())) {
                    sysUser.setPosition("物业管理员");
                    sysUser = sysUserService.update(sysUser);
                    addSysUserRole(result, sysUser.getId(), 3L);
                } else if ("3".equals(record.getOrgaType())) {
                    sysUser.setPosition("小区管理员");
                    sysUser = sysUserService.update(sysUser);
                    addSysUserRole(result, sysUser.getId(), 4L);
                }
            }
            if ("3".equals(record.getOrgaType())) {
                TVillage village = new TVillage().setOrgaId(result.getId()).setVillageName(record.getOrgaName());
                if (sysUser != null) {
                    village.setManagerId(sysUser.getId());
                }
                village.setCreateBy(result.getUpdateBy());
                village.setUpdateBy(result.getUpdateBy());
                villageService.update(village);
            }
        }
        return result;
    }

    private void addSysUserRole(SysOrganization result, Long userId, Long roleId) {
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(userId);
        sysUserRole.setRoleId(roleId);
        sysUserRole.setCreateBy(result.getUpdateBy());
        sysUserRole.setUpdateBy(result.getUpdateBy());
        sysUserRole.setCreateTime(new Date());
        sysUserRole.setUpdateTime(new Date());
        sysUserRoleMapper.insert(sysUserRole);
    }

    @Override
    public List<SysOrganization> queryList(Map<String, Object> params) {
        List<SysOrganization> list = super.queryList(params);
        for (SysOrganization sysOrganization : list) {
            if (sysOrganization.getParentId() != null && sysOrganization.getParentId() != 0) {
                SysOrganization parent = super.queryById(sysOrganization.getParentId());
                if (parent != null) {
                    sysOrganization.setParentName(parent.getOrgaName());
                } else {
                    sysOrganization.setParentId(null);
                }
            }
        }
        return list;
    }

    @Override
    @Cacheable("getChildrenId")
    public List<Long> getChildrenId(Long orgaId) {
        List<SysOrganization> list = queryList(InstanceUtil.newHashMap());
        List<Long> resultList = InstanceUtil.newArrayList();
        Map<Long, List<SysOrganization>> map = InstanceUtil.newHashMap();
        for (SysOrganization organization : list) {
            if (organization != null) {
                if (organization.getId() == orgaId) {
                    resultList.add(organization.getId());
                }
                if (organization.getParentId() != null && organization.getParentId() != 0) {
                    if (map.get(organization.getParentId()) == null) {
                        map.put(organization.getParentId(), new ArrayList<SysOrganization>());
                    }
                    map.get(organization.getParentId()).add(organization);
                }
            }
        }
        for (SysOrganization organization : getChildren(orgaId, map)) {
            resultList.add(organization.getId());
        }
        return resultList;
    }

    @Override
    @Cacheable("getChildren")
    public List<SysOrganization> getChildren(Long orgaId) {
        List<SysOrganization> list = queryList(InstanceUtil.newHashMap());
        List<SysOrganization> resultList = InstanceUtil.newArrayList();
        Map<Long, List<SysOrganization>> map = InstanceUtil.newHashMap();
        for (SysOrganization organization : list) {
            if (organization != null) {
                if (organization.getId() == orgaId) {
                    resultList.add(organization);
                }
                if (organization.getParentId() != null && organization.getParentId() != 0) {
                    if (map.get(organization.getParentId()) == null) {
                        map.put(organization.getParentId(), new ArrayList<SysOrganization>());
                    }
                    map.get(organization.getParentId()).add(organization);
                }
                if (organization.getManagerId() != null) {
                    SysUser sysUser = sysUserService.queryById(organization.getManagerId());
                    if (sysUser != null) {
                        organization.setManagerAccount(sysUser.getAccount());
                        organization.setManagerName(sysUser.getUserName());
                        organization.setManagerPhone(sysUser.getPhone());
                    }
                }
            }
        }
        resultList.addAll(getChildren(orgaId, map));
        return resultList;
    }

    private List<SysOrganization> getChildren(Long orgaId, Map<Long, List<SysOrganization>> map) {
        List<SysOrganization> children = map.get(orgaId);
        if (children == null) {
            return InstanceUtil.newArrayList();
        }
        List<SysOrganization> resultList = InstanceUtil.newArrayList();
        resultList.addAll(children);
        for (SysOrganization sysOrganization : children) {
            resultList.addAll(getChildren(sysOrganization.getId(), map));
        }
        return resultList;
    }
}
